import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/others/common_enum/cycling_record_filter_type.dart';
import 'package:inmotion_pro/pages/others/custom_view/others/refresh_view.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../service/cache_config_service.dart';
import '../../../service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_once.dart';
import '../../../utils/date_format_util.dart';
import 'controller.dart';

// 骑行记录详情页
class CyclingRecordListView extends BaseGetView<CyclingRecordListController> {
  CyclingRecordListView({super.key});

  @override
  String? get title => local.cycling_record;

  // 获取所有不重复的年份
  List<int> get _availableYears {
    // 当前年份前推三年
    final currentYear = DateTime.now().year;
    final years = <int>{};
    for (int i = 0; i < 3; i++) {
      years.add(currentYear - i);
    }
    return years.toList();
  }

  // 获取某年的所有月份
  List<int> _getMonthsForYear(int year) {
    // 12个月份
    final months = <int>{};
    for (int i = 1; i <= 12; i++) {
      months.add(i);
    }
    return months.toList();
  }

  @override
  Widget buildBody(BuildContext context) {
    return Material(
      color: Colors.black,
      child: Obx(
        () => Column(
          children: [
            // 筛选控件
            SizedBox(
              width: double.infinity,
              child: _buildFilterSection(),
            ),

            // 统计信息
            _buildStatistics(),

            // 记录列表
            _buildRecordsList(),
          ],
        ),
      ),
    );
  }

  Widget _buildFilterSection() {
    return Container(
      padding: EdgeInsets.all(CONTENT_MARGIN),
      decoration: const BoxDecoration(
        color: Colors.black,
        border: Border(bottom: BorderSide(color: GrayColor.gray2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            local.recent_cycling_record(local.three),
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 12.w),
          Center(
            child: Obx(() {
              const filterTypes = CyclingRecordFilterType.values;
              return ToggleButtons(
                isSelected: filterTypes
                    .map((type) =>
                        controller.state.currentFilterType.value == type)
                    .toList(),
                onPressed: (index) {
                  controller.state.currentFilterType.value = filterTypes[index];
                  switch (filterTypes[index]) {
                    case CyclingRecordFilterType.all:
                      controller.state.currentYear.value = 0;
                      controller.state.currentMonth.value = 0;
                      break;
                    case CyclingRecordFilterType.year:
                      controller.state.currentMonth.value = 0;
                      break;
                    case CyclingRecordFilterType.month:
                      break;
                  }
                },
                borderRadius: BorderRadius.circular(8),
                color: Colors.white.withOpacity(0.6),
                selectedColor: Colors.white,
                borderWidth: 1,
                borderColor: const Color(0xFFFBFBFB).withOpacity(0.6),
                selectedBorderColor: const Color(0xFFFBFBFB),
                fillColor: LxCol.theme,
                constraints: BoxConstraints.expand(
                  width: (ScreenUtil().screenWidth - CONTENT_MARGIN * 3) /
                      filterTypes.length,
                  height: 45.w,
                ),
                children: filterTypes.map((type) {
                  return Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Text(type.title),
                  );
                }).toList(),
              );
            }),
          ),
          SizedBox(height: CONTENT_MARGIN),
          Visibility(
            visible: controller.state.currentFilterType.value !=
                CyclingRecordFilterType.all,
            child: _buildDateSelector(),
          ),
        ],
      ),
    );
  }

  Widget _buildDateSelector() {
    return Row(
      children: [
        // 年份选择
        Expanded(
          child: DropdownButtonFormField<int>(
            value: controller.state.currentYear.value == 0
                ? null
                : controller.state.currentYear.value,
            decoration: InputDecoration(
              labelText: local.select_year,
              labelStyle: const TextStyle(fontSize: 14),
              border: const OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(8)),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(8)),
                borderSide: BorderSide(
                    color: const Color(0xFFFBFBFB).withOpacity(0.6),
                    width: 1.0),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: const BorderRadius.all(Radius.circular(8)),
                borderSide: BorderSide(
                    color: const Color(0xFFFBFBFB).withOpacity(0.6),
                    width: 1.0),
              ),
              floatingLabelStyle: TextStyle(
                color: const Color(0xFFFBFBFB).withOpacity(0.6),
              ),
              focusColor: const Color(0xFFFBFBFB).withOpacity(0.6),
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            ),
            items: _availableYears.map((year) {
              return DropdownMenuItem(
                value: year,
                child: Text('$year'),
              );
            }).toList(),
            onChanged: (value) {
              controller.state.currentYear.value = value ?? 0;
            },
          ),
        ),
        if (controller.state.currentFilterType.value ==
                CyclingRecordFilterType.month &&
            controller.state.currentYear.value != 0) ...[
          SizedBox(width: 12.w),
          Expanded(
            child: DropdownButtonFormField<int>(
              value: controller.state.currentMonth.value == 0
                  ? null
                  : controller.state.currentMonth.value,
              decoration: InputDecoration(
                labelText: local.select_month,
                labelStyle: const TextStyle(fontSize: 14),
                border: const OutlineInputBorder(),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.white.withOpacity(0.4), width: 1.0),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.white.withOpacity(0.4), width: 1.0),
                ),
                floatingLabelStyle: TextStyle(
                  color: Colors.white.withOpacity(0.4),
                ),
                focusColor: Colors.white.withOpacity(0.4),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
              ),
              items: _getMonthsForYear(controller.state.currentYear.value)
                  .map((month) {
                return DropdownMenuItem(
                  value: month,
                  child: Text(DateFormatUtil.getMonth(month)),
                );
              }).toList(),
              onChanged: (value) {
                controller.state.currentMonth.value = value ?? 0;
              },
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildStatistics() {
    var speedObj = CacheConfigService.to
        .metricUnit(controller.state.rideRecordStats.value.mileage / 100);
    var totalDuration =
        Duration(seconds: controller.state.rideRecordStats.value.rideTime);
    var totalCalories = controller.state.rideRecordStats.value.consumption;
    return Container(
      padding: EdgeInsets.all(CONTENT_MARGIN),
      margin: EdgeInsets.all(CONTENT_MARGIN),
      decoration: BoxDecoration(
        color: const Color(0xFF00607A),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFF00607A)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Flexible(
            child: Wrap(
              alignment: WrapAlignment.spaceAround,
              spacing: 24.w,
              runSpacing: 12.w,
              children: [
                _buildStatItem(local.total_mileage,
                    '${speedObj.$1.toStringAsFixed(1)} ${speedObj.$2}'),
                _buildStatItem(
                  local.total_duration,
                  totalDuration.inHours > 0
                      ? '${totalDuration.inHours}${local.h}${totalDuration.inMinutes.remainder(60)}${local.min}'
                      : '${totalDuration.inMinutes}${local.min}',
                ),
                _buildStatItem(local.total_power,
                    '${(totalCalories / 1000).toStringAsFixed(1)} kwh'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 4.w),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: GrayColor.gray6,
          ),
        ),
      ],
    );
  }

  Widget _buildRecordsList() {
    return Expanded(
      child: LxRefreshView(
        onRefresh: () => controller.refreshCyclingRecords(),
        onLoadMore: () => controller.loadMoreCyclingRecords(),
        noMoreData: !controller.state.hasMore.value,
        child: controller.state.cyclingRecords.isEmpty
            ? LxEmptyView(emptyMessage: local.no_cycling_record)
            : ListView.separated(
                itemCount: controller.state.cyclingRecords.length,
                itemBuilder: (BuildContext context, int index) {
                  final record = controller.state.cyclingRecords[index];
                  return Padding(
                    padding: EdgeInsets.only(
                      left: CONTENT_MARGIN,
                      right: CONTENT_MARGIN,
                    ),
                    child: _buildRecordCard(record),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return const SizedBox.shrink();
                },
              ),
      ),
    );
  }

  Widget _buildRecordCard(VehicleStatisticsOnce record) {
    var mileage = CacheConfigService.to.metricUnit(record.singleMileage);
    var avgSpd = CacheConfigService.to.metricUnit(record.avgSpeed);
    return Card(
      margin: EdgeInsets.only(bottom: 12.w),
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(CONTENT_MARGIN),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${record.date.year}-${record.date.month.toString().padLeft(2, '0')}-${record.date.day.toString().padLeft(2, '0')} ${record.date.hour.toString().padLeft(2, '0')}:${record.date.minute.toString().padLeft(2, '0')}',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.w),
                  decoration: BoxDecoration(
                    color: LxCol.theme,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    '${mileage.$1.toStringAsFixed(1)} ${mileage.$2}',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 8.w),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildRecordDetail(local.duration,
                    '${record.ridingDuration.inHours}${local.h}${(record.ridingDuration.inMinutes.remainder(60))}${local.min}'),
                _buildRecordDetail(local.average_speed,
                    '${avgSpd.$1.toStringAsFixed(1)} ${avgSpd.$2}/h'),
                _buildRecordDetail(local.power,
                    '${(record.singleConsumption / 1000).toStringAsFixed(1)} kwh'),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRecordDetail(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(fontSize: 12, color: Colors.white.withOpacity(0.5)),
        ),
        SizedBox(height: 2.w),
        Text(
          value,
          style: const TextStyle(
              fontSize: 14, fontWeight: FontWeight.w500, color: Colors.white),
        ),
      ],
    );
  }
}

class NoisyContainer extends StatelessWidget {
  final Color color;
  final double? width;
  final double? height;
  final double noiseIntensity;
  final Widget? child;

  const NoisyContainer({
    super.key,
    required this.color,
    this.width,
    this.height,
    this.noiseIntensity = 0.1,
    this.child,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      child: Stack(
        children: [
          // 基础颜色层
          Container(color: color),

          // 噪点层
          _buildNoiseLayer(),

          // 子组件
          if (child != null) child!,
        ],
      ),
    );
  }

  Widget _buildNoiseLayer() {
    return CustomPaint(
      painter: _NoiseLayerPainter(noiseIntensity),
      size: Size.infinite,
    );
  }
}

class _NoiseLayerPainter extends CustomPainter {
  final double intensity;
  final Random random = Random();

  _NoiseLayerPainter(this.intensity);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    final noiseCount = (size.width * size.height * 0.01).toInt();

    for (int i = 0; i < noiseCount; i++) {
      final x = random.nextDouble() * size.width;
      final y = random.nextDouble() * size.height;
      final alpha = random.nextDouble() * intensity;

      // 随机选择亮色或暗色噪点
      final isLight = random.nextBool();
      final noiseColor = isLight
          ? Colors.white.withOpacity(alpha)
          : Colors.black.withOpacity(alpha);

      paint.color = noiseColor;
      canvas.drawCircle(Offset(x, y), 0.3 + random.nextDouble() * 0.7, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
